package com.mlatent.mvvmproject.app.util

import android.text.TextUtils
import com.google.gson.Gson
import com.mlatent.mvvmproject.data.model.UserInfoResponse
import com.tencent.mmkv.MMKV

/**
 * Created by lihao on 2020/5/18.
 * Describe: 用于存储一些持久信息
 */
object CacheUtils {

    private const val CACHE_FILE_NAME = "app"

    val mmkv: MMKV by lazy {
        MMKV.mmkvWithID(CACHE_FILE_NAME)
    }

    /**
     * 是否第一次打开
     */
    fun isFirst(): Boolean {
        return mmkv.decodeBool("first")
    }

    /**
     * 设置第一次打开
     */
    fun setFirst(isFirst: Boolean) {
        mmkv.encode("first", isFirst)
    }

    fun setUserInfo(userInfo: UserInfoResponse?) {
        if (userInfo != null) {
            mmkv.encode("userInfo", Gson().toJson(userInfo))
            setLogin(true)
        } else {
            setLogin(false)
        }
    }

    fun getUserInfo(): UserInfoResponse? {
        val userStr = mmkv.decodeString("userInfo")
        return if (TextUtils.isEmpty(userStr))
            null
        else
            Gson().fromJson(userStr, UserInfoResponse::class.java)
    }

    fun isLogin(): Boolean {
        return mmkv.decodeBool("isLogin", false)
    }

    fun setLogin(isLogin: Boolean) {
        mmkv.encode("isLogin", isLogin)
    }
}